/*
 * CouponDAO.java
 *
 * Created on March 5, 2007, 8:07 PM
 *
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.*;
import java.sql.*;
import java.util.ArrayList;

/**Reads and writes CouponBO data to and from the database.
 *
 * @author Travis Kulbeth
 */
public class CouponDAO {
    
    /** Contains an instance of CouponDAO*/
    private static CouponDAO instance = null;
    
    /** Creates a new instance of CouponDAO */
    public CouponDAO() {
    }
    
    /**Retrieves an instance of the CouponDAO object
     *
     * @return a current singleton instance of the CouponDAO class
     */
    public static synchronized CouponDAO getInstance() {
        if (instance == null) {
            instance = new CouponDAO();
        }
        return instance;
    }
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   CREATE
    /**
     * Creates a new CouponBO object with a newly generated GUID.
     * 
     * @return a newly created CouponBO with unique GUID
     * @throws java.lang.Exception to catch any errors in the creation process.
     */
    public CouponBO create() throws Exception{
        String id = GUID.generate();
        CouponBO bo = new CouponBO(id);
        Cache c = Cache.getInstance();
        c.put(bo.getCouponID(), bo);
        return bo;
    }
    
    //////////////////////////////////////////////////////////////////////////////
    //////////   READ
    /**
     * This is the public read statement.  It loads an existing Coupon record
     * from the database based on the Coupon id and returns a CouponBO.
     * 
     * @return a CouponBO containing the information extracted from the requested
     * tuple in the DB.
     * @param id contains the unique identifier for the record to be read from the DB.
     * @throws edu.byu.isys413.group1E.DataException to catch any errors with the incoming data
     * @throws edu.byu.isys413.group1E.ConnectionPoolException to catch errors when connecting to the DB
     */
    public synchronized CouponBO read(String id) throws DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        CouponBO coup = (CouponBO)c.get(id);
        if (coup != null){
            return coup;                                                        // if so, return it immediately
        }
        
        //otherwise, get it from the database
        try {
            Connection conn = ConnectionPool.getInstance().get();             // retrieve a database connection from the pool
            coup = this.read(id, conn);                                              // call read with a connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id = " + id, e);
        }catch (ConnectionPoolException x) {
            //rollback
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return coup;
    }
    
    
    /**
     * This is the public read statement.  It loads an existing Coupon record
     * from the database based on the Coupon id, using an already existing connection to the DB,
     * and returns a CouponBO.
     * 
     * 
     * @return CouponBO
     * @param id contains the given id for the Coupon to be read
     * @param conn contains an already open connection to the DB
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    synchronized CouponBO read(String id, Connection conn) throws SQLException, DataException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        CouponBO coup = (CouponBO)c.get(id);
        if (coup != null){
            return coup;                                                        // if so, return it immediately
        }
        
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM Coupon WHERE CouponID = '" + id + "'");
        conn.commit();
        
        //build the object from the result set
        if (rs.next()) {
            coup = new CouponBO(rs.getString("CouponID"));
            coup.setRevSrcType(rs.getString("TypeRS"));
            coup.setCoupAmount(rs.getDouble("Amount"));
            coup.setCoupPercent(rs.getDouble("Percentage"));
            coup.setStartDate(rs.getDate("StartDate").toString());
            coup.setExpireDate(rs.getDate("ExpireDate").toString());
            coup.setDescription(rs.getString("Description"));
            coup.setAlreadyInDB(true);
            coup.setIsDirty(false);
            
            // save to the cache
            c.put(coup.getCouponID(), coup);
        }else{
            throw new DataException("Object was not found in the database.");
        }
        stmt.close();
        // return the BO
        return coup;
    }
    
    /**This is a public method to retrieve a list of all Coupons in the DB.
     * 
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     * @return a list of all Coupons from the DB.
     */
    public synchronized ArrayList<CouponBO> readAllCoup() throws DataException, SQLException, ConnectionPoolException{
        ArrayList<CouponBO> coupList = new ArrayList<CouponBO>();
        //now build the query
        String query = "SELECT * FROM Coupon";

        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        //build the object from the result set
        //build the object from the result set
        while (rs.next()) {
            CouponBO coup = new CouponBO(rs.getString("CouponID"));
            coup.setRevSrcType(rs.getString("TypeRS"));
            coup.setCoupAmount(rs.getDouble("Amount"));
            coup.setCoupPercent(rs.getDouble("Percentage"));
            coup.setStartDate(rs.getDate("StartDate").toString());
            coup.setExpireDate(rs.getDate("ExpireDate").toString());
            coup.setDescription(rs.getString("Description"));
            coup.setAlreadyInDB(true);
            coup.setIsDirty(false);

            // save to the list
            coupList.add(coup);
        }//while
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return coupList;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /** This is the public save method.  It is what is called when
     * the user (controller) wants to save or update an object
     * into the database.
     * 
     * @param coupIn is a CouponBO object to be saved
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     */
    public synchronized void save(CouponBO coupIn) throws DataException, ConnectionPoolException {
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            try {
                this.save(coupIn, conn);                                   // call save with a connection
                conn.commit();
            } catch (ConnectionPoolException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (DataException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (SQLException ex) {
                conn.rollback();
                ex.printStackTrace();
                throw new SQLException();
            }
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            // rollback
            throw new DataException("Error saving record for Coupon ID =" + coupIn.getCouponID(), e);
        }catch (ConnectionPoolException x){
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /** This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CouponDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.
     * 
     * @param coup contains the CouponBO to be saved
     * @param conn contains the Connection that has been established to the DB
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     */
    synchronized void save(CouponBO coup, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // run update or insert
        if (coup.isIsDirty()) {
            if (coup.isAlreadyInDB()) {
                update(coup, conn);
            }else{
                insert(coup, conn);
            }
            // set the dirty flag to false now that we've saved it
            coup.setIsDirty(false);
        }

                
        // touch the cache for the object
        Cache c = Cache.getInstance();
        c.put(coup.getCouponID(), coup);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * 
     * @param coup contains the CouponBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     */
    private synchronized void update(CouponBO coup, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("UPDATE Coupon SET TypeRS = ?, Amount = ?, " +
                "Percentage = ?, StartDate = ?, ExpireDate = ?, Description = ? WHERE CouponID = ?");
        pstmt.setString(1, coup.getRevSrcType());
        pstmt.setDouble(2, coup.getCoupAmount());
        pstmt.setDouble(3, coup.getCoupPercent());
        pstmt.setDate(4, java.sql.Date.valueOf(coup.getStartDate()));
        pstmt.setDate(5, java.sql.Date.valueOf(coup.getExpireDate()));
        pstmt.setString(6, coup.getDescription());
        pstmt.setString(7, coup.getCouponID());        
        pstmt.executeUpdate();
        pstmt.close();
        coup.setAlreadyInDB(true);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * @param coup contains the CouponBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     */
    private synchronized void insert(CouponBO coup, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Coupon (CouponID, TypeRS, Amount, Percentage, " +
                "StartDate, ExpireDate, Description) VALUES (?, ?, ?, ?, ?, ?, ?)");
        pstmt.setString(1, coup.getCouponID()); 
        pstmt.setString(2, coup.getRevSrcType());
        pstmt.setDouble(3, coup.getCoupAmount());
        pstmt.setDouble(4, coup.getCoupPercent());
        pstmt.setDate(5, java.sql.Date.valueOf(coup.getStartDate()));
        pstmt.setDate(6, java.sql.Date.valueOf(coup.getExpireDate()));
        pstmt.setString(7, coup.getDescription());
        pstmt.executeUpdate();
        pstmt.close();
        coup.setAlreadyInDB(true);
    }
    
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   DELETE
    
    /** I did not include the DELETE functionality intentionally due to instructions received, as well as
     * to protect the integrity of the data.
     */
}
